/*
 * @Author: your name
 * @Date: 2020-08-13 11:28:05
 * @LastEditTime: 2020-09-23 11:47:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \PipeOneMap_WebClient\src\app\business\home\form-constor\form-constor.component.ts
 */
import { Component, OnInit, Input, EventEmitter, Output, OnChanges, OnDestroy,  } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { FormBase } from './form-base';
import { FormControlService } from './form-control.service';
import { FormService } from './form.service';


@Component({
  selector: 'app-form-constor',
  templateUrl: './form-constor.component.html',
  styleUrls: ['./form-constor.component.scss']
})

export class FormConstorComponent implements OnInit, OnChanges, OnDestroy {
  // tslint:disable-next-line:no-inferrable-types
  isShow: boolean = false;
  isOpen = true;
  @Input() conditionList = null;
  @Input() conditionShow = null;
  @Output() propertyinfo = new EventEmitter<any>();
  @Output() layerInfoClose = new EventEmitter<any>();
  @Output() removeLayer = new EventEmitter<any>();
  selectValue = 't_text';

  validateForm!: FormGroup;
  listOfControl = [];
  maxNumberVlaue = 0;
  minNumberVlaue = 0;
  precision = 2;
  constructor(
    private fb: FormBuilder,
    private formControlService: FormControlService,
    private formService: FormService) { }
  protypeBtn() {
    this.isShow = !this.isShow;
  }
  ngOnInit() {
    this.validateForm = this.fb.group({});
    const defaulter = this.getChecked(this.conditionList);
    this.addField(defaulter);
  }

  getChecked(arr) {
    if (!Array.isArray(arr)) {
      return;
    }
    const choosItem = arr.filter(item =>
      item.enable === '1');
    return choosItem;
  }
  addField(addItem): void {
    if (!Array.isArray(addItem)) {
      return;
    }
    // const selectItem = this.formTypes.find(i => i.type === this.selectValue);
    // const control = { id: selectItem.fieldId, controlInstance: selectItem.fieldId, data: selectItem };
    this.removeAllField();
    addItem.forEach(element => {
      if (element.type === 't_numeric_range') {
        const control = { id: element.fieldId, controlInstance: element.fieldId, data: element };
        const index = this.listOfControl.push(control);
        this.validateForm.setControl(`numberRange-${element.fieldId}`, new FormGroup({
          maxNum: new FormControl(null),
          minNum: new FormControl(null)
        }));
      } else {
        const control = { id: element.fieldId, controlInstance: element.fieldId, data: element };
        const index = this.listOfControl.push(control);
        this.validateForm.addControl(
          this.listOfControl[index - 1].controlInstance,
          new FormControl(null)
        );
      }
    });

  }
  mouseenter() {
    this.isShow = true;
  }
  mouseleave() {
    this.isShow = false;
  }
  removeAllField() {
    this.listOfControl = [];
    this.listOfControl.forEach(element => {
      this.validateForm.removeControl(element.controlInstance);
    });
  }
  removeField(item: { id: number; controlInstance: string }, e: MouseEvent): void {
    e.preventDefault();
    if (this.listOfControl.length > 1) {
      const index = this.listOfControl.indexOf(item);
      this.listOfControl.splice(index, 1);
      this.validateForm.removeControl(item.controlInstance);
    }
  }
  chooselog(value: string[]): void {
    const choosItems = [];
    const choosItem = this.conditionList.filter(item => {
      return (value.indexOf(item.fieldId) > -1);
    });
    choosItems.push(...choosItem);
    this.addField(choosItems);
  }
  submitForm(): void {
    // 移除选中图层
    this.removeLayer.emit(true);
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    const dealData = this.dealObjectValue(this.validateForm.value);
    this.propertyinfo.emit(this.paramFormate(dealData));
    this.isShow = false;
  }
  dealObjectValue(obj) {
    const param = {};
    if (obj === null || obj === undefined || obj === '') { return param; }
    for (const key in obj) {
      if (this.dataType(obj[key]) === 'Object') {
        param[key] = this.dealObjectValue(obj[key]);
      } else if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
        param[key] = obj[key];
      }
    }
    return param;
  }
  dataType(obj) {
    if (obj === null) { return 'Null'; }
    if (obj === undefined) { return 'Undefined'; }
    return Object.prototype.toString.call(obj).slice(8, -1);
  }

  paramFormate(obj){
    const propertyParams = [];
    const { keys, values, entries} = Object;
    for (const [key, value] of entries(obj)) {
      const params = {};
      if (key.indexOf('numberRange') > -1 && Object.keys(value).length > 0){
        params['fieldId'] = key.split('-')[1];
        params['value'] = `${value['minNum'] ? value['minNum'] : 'limit'},${value['maxNum'] ? value['maxNum'] : 'limit'}`;
      }
      else if (key.indexOf('numberRange') > -1 && Object.keys(value).length === 0){
        params['fieldId'] = key.split('-')[1];
        params['value'] = null;
      }
      else {
        params['fieldId'] = key;
        params['value'] = value;
      }
      propertyParams.push(params);
    }
    return propertyParams ;
  }
  clickSwitch(e){
    this.layerInfoClose.emit(e);
  }
  ngOnChanges(){
    this.validateForm = this.fb.group({});
    const defaulter = this.getChecked(this.conditionList);
    this.addField(defaulter);
    this.isShow = true;
  }
  ngOnDestroy() {

  }
}
